package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping
    public R add(@RequestBody Category category) {
        categoryService.save(category);
        redisTemplate.delete("category");

        return R.success(null);
    }


    @GetMapping("/page")
    public R<Page<Category>> page(Integer page, Integer pageSize) {
        Page<Category> categoryPage = new Page<>(page, pageSize);
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        categoryService.page(categoryPage, queryWrapper);
        return R.success(categoryPage);
    }

    @GetMapping("/{id}}")
    public R<Category> getById(@PathVariable Long id) {
        Category byId = categoryService.getById(id);
        return R.success(byId);
    }

    @DeleteMapping
    public R deleteById(Long id) {
        categoryService.remove(id);
        redisTemplate.delete("category");

        return R.success("删除成功");
    }

    @PutMapping
    public R update(@RequestBody Category category) {
        categoryService.updateById(category);
        redisTemplate.delete("category");
        return R.success("更新成功");
    }

    @GetMapping("/list")
    public R<List<Category>> listByType(Integer type) {
        QueryWrapper<Category> dishQueryWrapper = new QueryWrapper<>();
        dishQueryWrapper.eq(!StringUtils.isEmpty(type), "type", type);
        ListOperations listOperations = redisTemplate.opsForList();
        List<Category> list = listOperations.range("category", 0, -1);
        if (null == list || list.size() == 0) {
            list = categoryService.list(dishQueryWrapper);
            listOperations.rightPushAll("category", list);
        }
        return R.success(list);
    }
}
